import { app, shell, BrowserWindow,ipcMain,dialog ,utilityProcessf} from 'electron'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
const { fork } = require('child_process')
// import utilityProcess from "Electron.utilityProcess";

// import {spawn} from 'child_process'
const path = require('path');

// 获取 userData 路径
const userDataPath = app.getPath('userData');

/////////////////////操作数据库start/////////////////////////
const sqlite3 = require('sqlite3').verbose();
let db;//db path
function initializeDatabase(userDataPath) {
  const dbPath = path.join(userDataPath, 'data.db');

  // 连接到 SQLite 数据库文件
  db = new sqlite3.Database(dbPath, (err) => {
    if (err) {
      console.error(err);
    } else {
      console.log('已连接到数据库。');
    }
  });

  // 创建表格
  db.serialize(() => {
    db.run('CREATE TABLE IF NOT EXISTS task (id INTEGER PRIMARY KEY AUTOINCREMENT,task_name TEXT,create_time TEXT)');//初始化任务表
    db.run('CREATE TABLE IF NOT EXISTS sub_task (id INTEGER PRIMARY KEY AUTOINCREMENT,p_id INTEGER,name TEXT,create_time TEXT)');//初始化子任务表
    db.run('CREATE TABLE IF NOT EXISTS track (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,transaction_table_id INTEGER,level INTEGER,sub_task_id INTEGER,parent_id INTEGER)');//初始化追踪表
  });
}
//判断任务是否存在
function checkTaskNameExists(taskName) {
  return new Promise((resolve, reject) => {
    const checkQuery = `SELECT COUNT(*) as count FROM task WHERE task_name = ?`;
    db.get(checkQuery, [taskName], (err, row) => {
      if (err) {
        reject(err);
      } else {
        const count = row.count;
        resolve(count > 0);
      }
    });
  });
}
//回调函数修改
const util = require('util');
// 将基于回调的异步函数转换为基于 Promise 的函数
const executeQuery = util.promisify((sql, callback) => {
  db.all(sql, (err, rows) => {
    if (err) {
      console.error(err);
      callback(err, null);
    } else {
      callback(null, rows);
    }
  });
});
const runSql = util.promisify((sql,callback) => {
  db.serialize(() => {
    db.run(sql, function(err) {
      if (err) {
        console.error(err);
        callback(err, null);
      } else {
        console.log('执行成功');
        callback(null,"success")
      }
    });
  });

});
function insertTask(task_name,create_time) {
  const insertSql = `INSERT INTO task ('task_name', 'create_time') VALUES ('${task_name}', '${create_time}')`
  return new Promise((resolve, reject) => {
    db.run(insertSql, function(err) {
      if (err) {
        reject(err);
      } else {
        resolve(this.lastID);
      }
    });
  });
}

function closeDatabase() {
  // 关闭数据库连接
  db.close((err) => {
    if (err) {
      console.error(err);
    } else {
      console.log('数据库连接已关闭。');
    }
  });
}
/////////////////////操作数据库end/////////////////////////

function createWindow() {
  // Create the browser window.
  let option = {
    width: 1200,
    height: 670,

    // x:3000,
    // y:200,
    show: false,
    autoHideMenuBar: true,
    alwaysOnTop:true,
    oneClick:false,
    allowToChangeInstallationDirectory:false,

    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: path.join(__dirname, '../preload/index.js'),
      sandbox: false,
      indeterminate:true
    }
  }
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    option.x = 3000
    option.y = 200
    option.autoHideMenuBar = false
  }
  const mainWindow = new BrowserWindow(option)

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'))
  }
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {

  // Set app user model id for windows
  electronApp.setAppUserModelId('com.electron')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  //init db
  initializeDatabase(userDataPath)
  //创建主窗口
  createWindow()

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })


})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    closeDatabase() //关闭数据库连接
    app.quit()
  }
})


//
// 解压ZIP文件并读取其中的CSV文件，并插入到SQLite数据库中


// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
// 监听渲染进程发送的查询请求
ipcMain.handle('query_db', async (event, sql) => {
  console.log(sql);
  try {
    // 执行查询操作，获取查询结果
    const rows = await executeQuery(sql);
    return rows
  } catch (error) {
    console.error(error);
  }
});

//创建任务
ipcMain.handle('create_task', async (event, request_data) => {
  try {
    console.log(request_data);
    const taskNameExists = await checkTaskNameExists(request_data.task_name); // 检查 task_name 是否存在的函数，请根据实际情况实现

    if (taskNameExists) {
      // 如果 task_name 已存在，可以在此处处理相应的逻辑，例如抛出一个错误或返回一个错误信息
      return 0
    }

    return insertTask(request_data.task_name, request_data.create_time)
      .then((insertedId) => {
        console.log('插入的自增 ID:', insertedId);
        const newTableName = `transaction_table_${insertedId}`;

        // 使用返回的自增 ID 创建新表
        const createTableSql = `CREATE TABLE IF NOT EXISTS ${newTableName} (
          j_y_k_h TEXT,
          j_y_z_h TEXT,
          c_x_f_k_j_g_y_y_y TEXT,
          j_y_h_m TEXT,
          j_y_z_j_h_m TEXT,
          j_y_s_j TEXT,
          j_y_j_e TEXT,
          j_y_y_e TEXT,
          s_f_b_z TEXT,
          j_y_d_s_z_h TEXT,
          x_j_b_z TEXT,
          d_s_h_m TEXT,
          d_s_s_f_z_h TEXT,
          d_s_k_h_y_h TEXT,
          z_h_s_m TEXT,
          j_y_b_z TEXT,
          j_y_w_d_m_c TEXT,
          j_y_f_s_d TEXT,
          j_y_s_f_c_g TEXT,
          p_h TEXT,
          IP_d_z TEXT,
          MAC_d_z TEXT,
          d_s_j_y_y_e TEXT,
          j_y_l_s_h TEXT,
          r_z_h TEXT,
          p_z_z_l TEXT,
          p_z_h TEXT,
          j_y_g_y_h_h TEXT,
          b_z TEXT,
          s_h_m_c TEXT,
          s_h_d_m TEXT,
          j_y_l_x TEXT,
          id INTEGER PRIMARY KEY AUTOINCREMENT
        )`;
        db.run(createTableSql, (err) => {
          if (err) {
            console.error(err);
          } else {
            console.log(`表 ${newTableName} 已成功创建`);
          }
        });
        return insertedId;
      })
      .catch((err) => {
        console.error(err);
        throw err;
      })
      .finally(() => {
        // 关闭数据库连接
        // db.close();
      });
  } catch (error) {
    console.error(error);
    throw error;
  }
});


ipcMain.handle('upload_file_to_db', async (event, task_id) => {
  return new Promise(async (resolve, reject) => {
    let info = '2';
    console.log(task_id, "aaa");
    const { filePaths } = await dialog.showOpenDialog({});

    if (filePaths && filePaths.length > 0) {
      const db = path.join(userDataPath, 'data.db');
      const csv_path = path.join(userDataPath, "csv_temp");
      const tableName = `transaction_table_${task_id}`;
      const childProcess = fork(path.join(__dirname, 'test_process.js'), [filePaths[0], csv_path, db, tableName]);

      childProcess.on('message', (message) => {
        console.log('子进程消息:', message);
      });

      childProcess.on('exit', (code) => {
        console.log('子进程退出，退出码:', code);
        info = '1';
        resolve(info); // 解析 Promise 并返回结果
      });
    } else {
      resolve(info); // 解析 Promise 并返回结果
    }
  });
});

ipcMain.handle('exec_db', async (event, sql) => {
  console.log(sql);
  try {
    // 执行查询操作，获取查询结果
    const rows = await runSql(sql);
    return rows;
  } catch (error) {
    console.error(error);
    // 如果出现错误，可以返回一个包含错误信息的对象
    return { error: error.message };
  }
});
